using System.Data;
using Dapper.Abstractions;
using Dapper.Extensions.Retry;
using Polly;

namespace Dapper.Extensions;

public class RetryDbConnectionFactoryDecorator(IDbConnectionFactory inner, RetryOptions retryOptions)
	: IDbConnectionFactory
{
	public IDbConnection CreateConnection()
	{

		var policy = Policy
			.Handle<Exception>()
			.WaitAndRetry(retryOptions.RetryCount, attempt => TimeSpan.FromMilliseconds(retryOptions.RetryDelayMilliseconds * attempt));

		return policy.Execute(inner.CreateConnection);
	}

	public async Task<IDbConnection> CreateConnectionAsync()
	{
		var policy = Policy
			.Handle<Exception>()
			.WaitAndRetryAsync(retryOptions.RetryCount, attempt => TimeSpan.FromMilliseconds(retryOptions.RetryDelayMilliseconds * attempt));

		return await policy.ExecuteAsync(inner.CreateConnectionAsync);
	}
}
